package com.bear.fastrepair.mvvm.data.employee

import android.util.Log
import com.bear.fastrepair.entity.*
import com.bear.fastrepair.http.api.UploadService
import com.bear.fastrepair.http.api.employee.BillService
import com.bear.fastrepair.http.api.employee.EmployeeImageService
import com.bear.fastrepair.http.api.employee.EmployeeService2
import com.bear.fastrepair.http.api.employee.OrderByEmployee
import com.bear.fastrepair.http.client.RetrofitManager
import com.bear.fastrepair.mvvm.data.MainDataSource
import com.bear.fastrepair.mvvm.data.Result
import com.bear.fastrepair.utils.ACCOUNT_TOKEN_KEY
import com.bear.fastrepair.utils.SharedPreferencesHelper
import com.bear.fastrepair.utils.URL_MOBILE
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import retrofit2.http.Body
import retrofit2.http.Path
import retrofit2.http.Url
import java.io.File

class EmployeeSource {

    private val main = MainDataSource()
    suspend fun getOrderInfoPage(
        current: Int,
        size: Int,
        orderStatus: Int?
    ): Result<EmployeeOrderInfoPage> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .getOrderInfoPageByEmployee(current, size, orderStatus).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun updateWorkStatus(workStatus: EmployeeWorkStatus): Result<ResponseInfo> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeService2::class.java, token)
            .updateWorkStatus(workStatus).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun updateApp() = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeService2::class.java, token)
            .updateApp().let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun downloadApp(@Url fileUrl: String) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeService2::class.java, token)
            .downloadApp(fileUrl).let {
                Result.Success(it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun updateLocation(location: UpdateLocation) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeService2::class.java, token)
            .updateLocation(location).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun resetPassword(resetPasswordBean: ResetPasswordBean) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeService2::class.java, token)
            .resetPassword(resetPasswordBean).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun getOrderById(id: String): Result<OrderInfoDetail> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .getOrderInfoById(id).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        Result.Error(e)
    }

    suspend fun saveBookingTime(serviceOrderId: String, bookingBody: BookingBody) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .saveBookingTime(serviceOrderId, bookingBody).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun imageUpload(path: String, params: List<File>): Result<ResponseListInfo> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        val map = hashMapOf<String, RequestBody>()
        val list = ArrayList<MultipartBody.Part>()
        params.forEachIndexed { index, item ->
//            val body = item.asRequestBody("multipart/form-data;charset=UTF-8".toMediaTypeOrNull())
//            map["img$index\"; filename=\"${item.name}"] = body
            val requestBody = item.asRequestBody("multipart/form-data".toMediaTypeOrNull())
            val body = MultipartBody.Part.createFormData("files", item.name, requestBody)
            list.add(body)
        }
        RetrofitManager.getServiceSetToken(URL_MOBILE, UploadService::class.java, token)
            .fileUpload(list).let {
                if (it.code == 0) Result.Success(it) else Result.Error(data = it)
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun employeeClockIn(
        locationAddress: String,
        locationLatitude: String,
        locationLongitude: String,
        serviceOrderId: String?
    ) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        val latitude = locationLatitude.toDouble()
        val longitude = locationLongitude.toDouble()
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .employeeClockIn(serviceOrderId, ClockInBody(locationAddress, latitude, longitude))
            .let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "employeeClockIn: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun takeMachineBack(
        serviceOrderId: String,
        images: String?,
        remark: String?
    ): Result<ResponseInfo> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .takeMachineBack(serviceOrderId, OrderCommonBody(images, remark)).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "takeMachineBack: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun takeMachineBackRepaired(
        serviceOrderId: String,
        images: String?,
        remark: String?
    ): Result<ResponseInfo> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .takeBackFixDone(serviceOrderId, OrderCommonBody(images, remark)).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "takeMachineBackRepaired: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun orderComplete(
        serviceOrderId: String,
        images: String?,
        remark: String?
    ): Result<ResponseInfo> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .orderComplete(serviceOrderId, OrderCommonBody(images, remark)).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "orderComplete: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun orderBack(
        serviceOrderId: String,
        images: String?,
        remark: String?
    ): Result<ResponseInfo> = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, OrderByEmployee::class.java, token)
            .orderSendBack(serviceOrderId, OrderCommonBody(images, remark)).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "orderBack: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun addOrderBill(billInfoAdd: BillInfoAdd) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, BillService::class.java, token)
            .addOrderBill(billInfoAdd).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "addOrderBill: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun getBillInfoById(id: String) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, BillService::class.java, token)
            .getBillInfoById(id).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "getBillInfoById: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun getImagesById(id: String) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeImageService::class.java, token)
            .getImagesById(id).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "getBillInfoById: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun uploadImages(image: EmployeeUploadImage) = try {
        val token = SharedPreferencesHelper.getString(ACCOUNT_TOKEN_KEY) ?: ""
        RetrofitManager.getServiceSetToken(URL_MOBILE, EmployeeImageService::class.java, token)
            .uploadImages(image).let {
                if (it.code == 0) Result.Success(it) else {
                    Log.i(javaClass.simpleName, "getBillInfoById: error msg ${it.msg}")
                    Result.Error(data = it)
                }
            }
    } catch (e: Exception) {
        e.printStackTrace()
        Result.Error(e)
    }

    suspend fun getPersonalInfo() = main.getEmployeePersonalInfo()



}